<template>
  <div>
    <table-search
      ref="tableSearch"
      :title="'商品列表( ' + totalNum + ' )'"
      selection
      :columns="columns"
      :api="getList"
      @selection-change="onSelectionChange"
    >
      <el-form
        slot="table-search"
        inline
        label-width="8em"
        size="medium"
        class="table-search"
      >
        <el-form-item label="项目名称：" class="purchasePlatformId">
          <el-select v-model="purchasePlatformId" placeholder="请选择项目名称">
            <el-option
              v-for="option in projectList"
              :key="option.value"
              :value="option.value"
              :label="option.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="table-title" style="text-align: right; flex: 1">
        <el-button type="primary" size="small" @click="onExportExcel"
          >下载EXCEL模板</el-button
        >
        <el-upload
          class="uploadBtn"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :action="uploadExcel.url"
          :name="uploadExcel.name"
          :accept="uploadExcel.accept"
          :data="{
            purchasePlatformName: purchasePlatformName,
            purchasePlatformId: purchasePlatformId,
          }"
          :disabled="!purchasePlatformId"
        >
          <el-button type="primary" size="small" :disabled="!purchasePlatformId"
            >EXCEL导入上架商品</el-button
          >
        </el-upload>
        <el-button
          type="primary"
          size="small"
          @click="onExport"
          :disabled="!selection.length"
          >导出所选商品</el-button
        >
      </div>

      <template #purchasePlatformName="{ row }">
        <span style="color: red">
          {{ row.purchasePlatformName || '-' }}
        </span>
      </template>

      <template #operate="{ row }">
        <router-link
          :to="`/admin/projectInfo/detail?id=${row.id}`"
          target="_blank"
        >
          <el-button type="text" size="small">查看详情</el-button>
        </router-link>
        <br />
        <el-button
          v-if="row.goodsSource == 2"
          type="text"
          size="small"
          @click="deleteGoods(row.id)"
          >删除</el-button
        >
      </template>
    </table-search>
  </div>
</template>

<script>
import {
  defineComponent,
  computed,
  reactive,
  getCurrentInstance,
  ref,
} from '@vue/composition-api'
import TableSearch from '@/components/TableSearch/TableSearch'
import { createTableColumns } from '@/components/TableSearch/utils'

import {
  pageOfAdmin,
  deleteGoodsById,
  downloadExcelTmpl,
} from '@/api/projectInfo'
import { downLoadFile } from '@/lib/utils'
import Http from '@/lib/http'

export default defineComponent({
  components: {
    TableSearch,
  },
  setup() {
    const instance = getCurrentInstance()

    // 获取项目名称列表
    const projectList = ref([])
    const purchasePlatformId = ref('')
    instance.$axios
      .get('/api/manage/projectInfo/queryPurchasePlatformName')
      .then(res => {
        if (res.success) {
          const list = []
          res.result.forEach(item => {
            list.push({ value: item.projectId, label: item.name })
          })
          projectList.value = list

          // 项目名称默认选择第一项
          purchasePlatformId.value = list[0].value
          // 触发搜索
          instance.$refs.tableSearch.onSearchSubmit()
          // 实时为purchasePlatformName赋值（EXCEL导入上架商品必传参数）
        } else instance.$message.error(res.desc)
      })

    const purchasePlatformName = computed(() => {
      let _value = ''
      if (projectList.value)
        projectList.value.some(function (item) {
          if (item.value == purchasePlatformId.value) {
            _value = item.label
            return true
          }
        })
      return _value
    })

    const columns = computed(() => {
      return createTableColumns([
        ['项目名称', 'purchasePlatformName'],
        [
          '创建时间',
          'createTime',
          { search: { key: ['createStartTime', 'createEndTime'] }, width: 100 },
        ],
        ['用户账户', 'userAccountName', { search: true }],
        ['公司名称', 'companyName', { search: true }],
        ['sku商品编码', 'skuId', { search: true }],
        ['商品名称', 'goodsName', { search: true }],
        ['类目', 'categoryName', { search: true }],
        ['品牌', 'brandName', { search: true }],
        ['型号', 'model', { search: true }],
        ['参数规格', 'spec', { search: true }],
        ['销售价格', 'salesPrice'],
        ['操作', 'operate'],
      ])
    })

    const totalNum = ref(0)
    // 获取列表
    const getList = async (startPage, size, query) => {
      if (purchasePlatformId.value)
        query['purchasePlatformId'] = purchasePlatformId.value

      const { goodsBaseInfo } = await pageOfAdmin(startPage, size, query)
      totalNum.value = goodsBaseInfo.total
      return goodsBaseInfo
    }

    // 多选
    const selection = ref([])
    const onSelectionChange = val => {
      selection.value = val
    }

    // 导出所选商品
    const onExport = () => {
      downLoadFile(
        Http.getUrl(
          `/manage/projectInfo/exportGoodsExcel?exportIds=${selection.value
            .map(item => item.id)
            .join(',')}`
        )
      )
    }

    // 下载EXCEL模板
    const onExportExcel = async () => {
      const res = await downloadExcelTmpl()
      downLoadFile(res)
    }

    // EXCEL导入上架商品
    const uploadSuccess = (res, file) => {
      if (res.success) {
        instance.$message({
          type: 'success',
          message: '导入上架商品成功',
        })
        instance.$refs.tableSearch.onSearchSubmit()
      } else instance.$message.error(res.desc)
    }
    const uploadExcel = {
      url: '/api/manage/projectInfo/importGoods',
      name: 'excel',
      accept: '.xls, .xlsx',
    }

    // 列表内删除商品
    const _deleteGoods = async id => {
      await deleteGoodsById({ id: id })
      instance.$message({
        type: 'success',
        message: '删除成功',
      })
      instance.$refs.tableSearch.onSearchSubmit()
    }
    const deleteGoods = id => {
      instance
        .$confirm(`是否删除该条商品？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          _deleteGoods(id)
        })
    }

    return {
      columns,
      getList,
      onSelectionChange,
      onExport,
      onExportExcel,
      selection,
      totalNum,
      uploadExcel,
      uploadSuccess,
      purchasePlatformName,
      purchasePlatformId,
      deleteGoods,
      projectList,
    }
  },
})
</script>

<style lang="scss" scoped>
.grey {
  color: #bbb;
}
.red {
  color: red;
}
.hasEdit {
  position: absolute;
  top: 0;
  left: 0;
  &::before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-top: 30px solid red;
    border-right: 30px solid transparent;
  }
  .text {
    position: absolute;
    top: -3px;
    left: 2px;
    color: #fff;
    font-size: 12px;
  }
}
.audit-detail {
  color: #000;
}
.audit-detail ::v-deep strong {
  color: red;
}
.uploadBtn {
  display: inline-block;
  margin: 0 10px;
}
.table-search {
  border-bottom: 2px dashed #ebeef5;
  margin-bottom: 22px;
}
</style>

<style lang="scss">
.prompt-refuse {
  width: 800px;
  textarea {
    height: 200px;
  }
}
.purchasePlatformId {
  label {
    &::before {
      display: inline-block;
      content: '*';
      color: #e51c23;
      margin-right: 2px;
    }
  }
}
</style>
